package per.lance.easytomcat.net;

import java.io.*;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;

public class HttpSocket {

    Socket socket;

    public HttpSocket(Socket socket) {
        this.socket = socket;
    }

    public HttpRequest getHttpRequest() throws IOException, URISyntaxException {
        HttpRequest httpRequest = new HttpRequest();
        InputStream in = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        java.lang.String line = "";
        int num = 1;
        String uriString = "";
        while (!"".equals((line = reader.readLine()))) {
            if (num == 1) {
                httpRequest.setMethod(line.split(" ")[0]);
                uriString = line.split(" ")[1];
                num++;
            } else {
                java.lang.String[] strs = line.split(": ");
                httpRequest.getRequestHeader().put(strs[0].toLowerCase(), strs[1]);
            }
            System.out.println(line);
        }
        if (!"get".equals(httpRequest.getMethod().toLowerCase())) {
            String strlen = httpRequest.getRequestHeader().get("Content-Length".toLowerCase());
            int len = Integer.parseInt(strlen);
            char[] buf = new char[len];
            reader.read(buf);
            String bodyStr = new String(buf);
            String[] bodyStrs = bodyStr.split("&");
            for(String str : bodyStrs){
                String[] params = str.split("=");
                httpRequest.getRequestBody().put(params[0], params[1]);
            }
        }
//        String contenType = httpRequest.getRequestHeader().get("content-type");
//        if ("POST".equals(httpRequest.getMethod().toLowerCase()) && contenType != null
//                && contenType.startsWith("multipart/form-data")) {
//            //文件上传的分割位 这里只处理单个文件的上传
//            String boundary = contenType.substring(contenType.indexOf("boundary") +
//                    "boundary=".length());
//
//        }
        uriString = "http://" + httpRequest.getRequestHeader().get("host").toString() + uriString;
        httpRequest.setUri(new URI(uriString));

        return httpRequest;
    }

    public HttpRespone getHttpRespone() throws IOException {
        HttpRespone httpRespone = new HttpRespone();
        httpRespone.setBos(new BufferedOutputStream(socket.getOutputStream()));
        return httpRespone;
    }
}
